// @ts-nocheck

import {API_BASE_URL,API_BASE_SITEMAP,API_BASE_WEAPONSPAGESIZE} from  "@/lib/config";

export const GET = async ({ fetch }) => {
    const site = API_BASE_SITEMAP;

    const navigation = [
      { loc: site, changefreq: 'daily', priority: 1.0 },
      { loc: `${site}/weapons`, changefreq: 'monthly', priority: 0.8 },
    ];

    let options = {
        table_name: "DestinyInventoryItemDefinition",
        filter_dict: {
            keys: ["stats.stats.2961396640.value", "itemTypeDisplayName", "stats.stats.447667954.value", "displayProperties.name", "hash", "stats.stats.4284893193.value"],
            filters: {
                itemType: 3,
            },
            advanced_filter: {
                standard_item: true,
            },
            search_list: [],
        },
        language: "zh-chs",
        is_fuzzy: true,
        priority_sort: false,
    };

    const response = await fetch(`${API_BASE_URL}/api/search`, {
        method: "POST",
        body: JSON.stringify(options),
        headers: {
            "Content-Type": "application/json",
        },
    });

    if (!response.ok) {
        throw new Error("Failed to fetch posts.");
    }

    const postsJson = await response.json();
    const posts = postsJson.Response;

    const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
      <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        ${navigation.map(nav => `
          <url>
            <loc>${nav.loc}</loc>
            <changefreq>${nav.changefreq}</changefreq>
            <priority>${nav.priority}</priority>
          </url>
        `).join('')}

        ${Array(Math.ceil(posts.length/API_BASE_WEAPONSPAGESIZE)).fill(1) 
            .map(
                (post,index) => `
        <url>
          <loc>${site}/weapons/${post+index}</loc>
          <changefreq>weekly</changefreq>
          <lastmod>${new Date().toISOString()}</lastmod>
        </url>
        `
            )
            .join("")}

            ${posts
            .map(
                (post) => `
        <url>
          <loc>${site}/weapons/${post}</loc>
          <changefreq>weekly</changefreq>
          <lastmod>${new Date().toISOString()}</lastmod>
        </url>
        `
            )
            .join("")}

        
      </urlset>`;

      

    return new Response(sitemap, {
        headers: {
            "Content-Type": "application/xml",
        },
    });
};
